package com.xxl.job.plus.executor.service.impl;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import org.springframework.stereotype.Service;

import com.xxl.job.plus.executor.config.XxlJobProperties;
import com.xxl.job.plus.executor.model.XxlJobGroup;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import com.xxl.job.plus.executor.service.JobGroupService;
import com.xxl.job.plus.executor.service.JobLoginService;
import lombok.RequiredArgsConstructor;

/**
 * @author : guorf
 * @version : v1.0
 * @description : TODO 任务分组
 * @createTime : 2023/4/23 9:50
 */
@Service
@RequiredArgsConstructor
public class JobGroupServiceImpl implements JobGroupService {

    private final XxlJobProperties xxlJobProperties;

    private final JobLoginService jobLoginService;

    /**
     * @description TODO 获取分组列表
     	 * @return java.util.List<cn.xslz.model.XxlJobGroup>
     **/
    @Override
    public List<XxlJobGroup> getJobGroup() {
        String url = xxlJobProperties.getAdmin().getAddresses()+"/jobgroup/pageList";
        HttpResponse response = HttpRequest.post(url)
                .form("appname", xxlJobProperties.getExecutor().getAppname())
                .form("title", xxlJobProperties.getExecutor().getTitle())
                .cookie(jobLoginService.getCookie())
                .execute();

        String body = response.body();
        JSONArray array = JSONUtil.parse(body).getByPath("data", JSONArray.class);
        List<XxlJobGroup> list = array.stream()
                .map(o -> JSONUtil.toBean((JSONObject) o, XxlJobGroup.class))
                .collect(Collectors.toList());

        return list;
    }

    /**
     * @description TODO 自动注册执行器
     * @return boolean
     **/
    @Override
    public boolean autoRegisterGroup() {
        String url = xxlJobProperties.getAdmin().getAddresses()+"/jobgroup/save";
        HttpRequest httpRequest = HttpRequest.post(url)
                .form("appname", xxlJobProperties.getExecutor().getAppname())
                .form("title", xxlJobProperties.getExecutor().getTitle());

        httpRequest.form("addressType",xxlJobProperties.getExecutor().getAddressType());
        if (xxlJobProperties.getExecutor().getAddressType().equals(1)){
            if (StrUtil.isBlank(xxlJobProperties.getExecutor().getAddressList())){
                throw new RuntimeException("手动录入模式下,执行器地址列表不能为空");
            }
            httpRequest.form("addressList",xxlJobProperties.getExecutor().getAddressList());
        }

        HttpResponse response = httpRequest.cookie(jobLoginService.getCookie())
                .execute();
        Object code = JSONUtil.parse(response.body()).getByPath("code");
        return code.equals(200);
    }

    /**
     * @description TODO 检查执行器是否注册
     * @return boolean
     **/
    @Override
    public boolean preciselyCheck() {
        List<XxlJobGroup> jobGroup = getJobGroup();
        Optional<XxlJobGroup> has = jobGroup.stream()
                .filter(xxlJobGroup -> xxlJobGroup.getAppname().equals(xxlJobProperties.getExecutor().getAppname())
                        && xxlJobGroup.getTitle().equals(xxlJobProperties.getExecutor().getTitle()))
                .findAny();
        return has.isPresent();
    }
}
